const mongoose = require('mongoose');
const Response = require('../utils/response');

class SchemaController {
    // 获取指定模型的字段信息
    async getModelSchema(ctx) {
        try {
            const { model } = ctx.params;
            
            // 获取所有已注册的模型
            const models = mongoose.models;
            const targetModel = models[model];

            if (!targetModel) {
                ctx.status = 404;
                ctx.body = Response.error(`模型 ${model} 不存在`, 404);
                return;
            }

            // 获取模型的 schema
            const schema = targetModel.schema;
            const paths = schema.paths;

            // 构建字段信息
            const fields = Object.keys(paths).map(path => {
                const fieldSchema = paths[path];
                return {
                    field: path,
                    type: fieldSchema.instance,
                    required: !!fieldSchema.options.required,
                    default: fieldSchema.options.default,
                    unique: !!fieldSchema.options.unique,
                    ref: fieldSchema.options.ref || null,
                    enum: fieldSchema.options.enum || null,
                    description: fieldSchema.options.description || '',
                    hidden: path === '__v' || path === '_id',
                };
            });

            // 获取索引信息
            const indexes = schema.indexes();

            ctx.body = Response.success({
                modelName: model,
                fields: fields.filter(f => !f.hidden), // 过滤掉隐藏字段
                indexes,
                timestamps: schema.options.timestamps || false,
            });

        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 获取所有可用的模型列表
    async getModels(ctx) {
        try {
            const { page = 1, limit = 10, name = '' } = ctx.query;
            const skip = (page - 1) * limit;

            // 获取所有模型
            const models = mongoose.models;
            
            // 根据名称过滤模型
            const filteredModels = Object.keys(models)
                .filter(modelName => 
                    modelName.toLowerCase().includes(name.toLowerCase())
                )
                .map(modelName => ({
                    name: modelName,
                    collection: models[modelName].collection.name
                }));

            // 计算总数
            const total = filteredModels.length;

            // 分页处理
            const paginatedModels = filteredModels.slice(skip, skip + Number(limit));

            ctx.body = Response.success({
                total,
                page: Number(page),
                limit: Number(limit),
                data: paginatedModels
            });
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 获取指定模型的数据列表
    async getModelData(ctx) {
        try {
            const { model } = ctx.params;
            const { page = 1, limit = 10, name = '' } = ctx.query;
            const skip = (page - 1) * limit;

            // 获取模型
            const targetModel = mongoose.models[ model];
            if (!targetModel) {
                ctx.status = 404;
                ctx.body = Response.error(`模型 ${model} 不存在`, 404);
                return;
            }

            // 构建查询条件
            const query = {};
            if (name) {
                // 如果模型有 name 字段，添加模糊查询
                const schema = targetModel.schema;
                if (schema.path('name')) {
                    query.name = { $regex: name, $options: 'i' };
                }
            }

            // 获取总数
            const total = await targetModel.countDocuments(query);

            // 获取分页数据
            const data = await targetModel
                .find(query)
                .skip(skip)
                .limit(Number(limit))
                .sort({ createdAt: -1 });

            ctx.body = Response.success({
                total,
                page: Number(page),
                limit: Number(limit),
                data
            });
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }
}

module.exports = new SchemaController(); 